package org.qiyu.live.account.provider.service.impl;

import jakarta.annotation.Resource;
import org.idea.qiyu.live.framework.redis.starter.keys.AccountProviderCacheKeyBuilder;
import org.qiyu.live.account.provider.service.IAccountTokenService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 作者：無言
 * 时间：2024/11/28 16:23
 * 描述：永无BUG
 */

@Service
public class AccountTokenServiceImpl implements IAccountTokenService {


    @Resource
    private AccountProviderCacheKeyBuilder accountProviderCacheKeyBuilder;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public String createAndSaveLoginToken(Long userId) {

        String token = UUID.randomUUID().toString();
        String key = accountProviderCacheKeyBuilder.buildUserLoginTokenKey(token);
        redisTemplate.opsForValue().set(key, userId.toString(), 30, TimeUnit.DAYS);
        return token;
    }

    @Override
    public Long getUserIdByToken(String tokenKey) {
        String key = accountProviderCacheKeyBuilder.buildUserLoginTokenKey(tokenKey);
        Integer userId = (Integer) redisTemplate.opsForValue().get(key);
        return userId == null ? null : Long.valueOf(userId);
    }
}
